<template>
  <div>
    <section class="findMain">

        <div class="topTitle blue getTop">
          <span class="goBack" @click="goBack"><i></i></span>
          动态圈
          <span @click="postNew" class="findClick"><i></i></span>
        </div>
        <div class="canvasBox">
          <canvas id="myCanvas"></canvas>
        </div>
      <scroller lock-x scrollbar-y use-pullup use-pulldown @on-pullup-loading="loadMore" @on-pulldown-loading="refresh" v-model="status" ref="scroller" :pulldown-config="{content:'下拉刷新',downContent:'下拉刷新',upContent:'释放刷新',loadingContent:'加载中'}" :pullup-config="{content:'',downContent:'',upContent:'',loadingContent:''}" >
   
        <div class="box2">
          <div class="findBanner" :class="{on:loadmoreStatic}">
              <img class="findBg" v-if="square_avatar!=''" :src="square_avatar">
              <img class="findBg" v-else :src="defLogo">
              <img class="logo" v-if="avatar!=''"  :src="avatar">
              <img class="logo" v-else :src="defLogo">
          </div>

          <div class="findNone" v-if="findNum!=''">
            <span @click="getAllMe">{{findNum}}条未读信息</span>
          </div>

          <div class="findlist">
              <div v-if="dataList.length<1" class="notHave">没有TA的动态</div>
              <div v-else class="item" v-for="(item,index) in dataList">
                  <img @click="goRouter(item.user.id)" class="logo" v-if="item.user.avatar!=''" :src="item.user.avatar">
                  <img @click="goRouter(item.user.id)" class="logo" v-else :src="defLogo">
                  <p class="title">{{item.user.nickname}}</p>
                  
                  
                  <div class="info">
                    {{item.say_content}}
                  </div>

                  <div v-if="item.say_image!=''" class="images">
                    <ul class="more" v-if="item.say_image.length>1">
                      <li @click="showBigImg(item.say_image,index)" v-for="(list,index) in item.say_image"><img v-lazy="list"></li>
                    </ul>
                    <ul class="once" v-else>
                      <li @click="showBigImg(item.say_image,index)" v-for="(list,index) in item.say_image"><img v-lazy="list"></li>
                    </ul>
                  </div>
                  
                  <div class="click">
                    <span class="time">{{item.created_at|getTime}}</span>
                    <span class="say" @click="clickSayBox(item,index)"><i></i></span>
                    <span v-if="item.me_like_id!=0" class="good on" @click="clickCloseZan(item)"><i></i></span>
                    <span v-else class="good" @click="clickZan(item)"><i></i></span>
                    <span class="goodNum">{{item.like_count}}</span>
                  </div>

                  <div class="sayBack">
                    <div class="sayTop">
                      <span></span>
                      <span></span>
                    </div>
                    <div class="sayList" v-if="item.user_comment!=''">
                      <p v-for="list in item.user_comment">
                        <span v-if="list.user.nickname!=''">{{list.user.nickname}}：</span>
                        <span v-else>{{list.user.id}}：</span>
                        {{list.content}}
                      </p>
                    </div>
                  </div>
              </div>
          </div>
        </div>

      </scroller>

        <div class="popBox" v-if="postStatic">
          <div class="info">
            <div>
              <textarea v-model="find.text" placeholder="这一刻的想法"></textarea>
              <div class="upImg">
                <img v-for="item in upImgList" :src="item" alt="">
                <a href="javascript:;" class="file addImg">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="file" @change="upImg" multiple  id="imgTest" class="mel" accept=".gif,.jpg,.jpeg,.png"></a>
              </div>
            </div>
            <div class="popClick">
              <span class="hui" @click="close">取消</span>
              <span @click="postFind">发表</span>
            </div>

          </div>
        </div>

        <div class="popBox" v-if="getStatic">
          <div class="info">
            <div>
              <textarea v-model="find.text" placeholder="这一刻的想法"></textarea>
            </div>
            <div class="popClick">
              <span class="hui" @click="close">取消</span>
              <span @click="clickSay">发表</span>
            </div>

          </div>
        </div>

      <swiper :data="imgDataPost" @close="closeSwiper" v-if="imgDataStatic"></swiper>
    </section>
  </div>
</template>

<script>
import axios from 'axios'
import {Post,Get,Put,Delete} from '@/config/api.js'
import { Scroller} from 'vux'
import { mapState } from 'vuex'
import swiper from '@/components/swiper'

export default {
  data () {
    return {
      n: 10,
      n1: 10,
      pullupEnabled: true,
      status: {
        pullupStatus: 'default',
        pulldownStatus: 'default'
      },
      loadmoreStatic:false,//还没有上拉
      defLogo:'../static/images/deflogo.jpg',
      dataList:'',
      logo:'',
      imgDataStatic:false,//相册弹窗
      imgDataPost:'',//相册要展示的照片

      upImgList:[],//待上传图片
      upImgKey:[],//上传图片key
      upImgNum:0,//已上传图片数量
      upImgAllNum:0,//上传图片总数量
      postStatic:false,//自己发表动态
      getStatic:false,//评论动态
      findNum:'',//未读评论
      id:'',//评论id
      num:'',//评论排序
      onPage:1,//当前页面
      allDataPage:'',//总页数
      find:{
        img:'',
        text:''
      }
    }
  },
  computed: {
    ...mapState({
      uid: state => state.uid,
      password: state => state.password,
      nickname: state => state.nickname,
      avatar: state => state.avatar,
      square_avatar: state => state.square_avatar,
    })
  },
  components: {
    Scroller,swiper
  },
  filters:{
    getTime(val){
      let nval=val.replace(" ","T")+'Z';
      let addTime=60*60*8
      var date1 = new Date(nval)
      var date2 = new Date()
      var s1 = date1.getTime(),s2 = date2.getTime();
      var total = (s2 - s1)/1000+28800;
      var day = parseInt(total / (24*60*60));//计算整数天数
      var afterDay = total - day*24*60*60;//取得算出天数后剩余的秒数
      var hour = parseInt(afterDay/(60*60));//计算整数小时数
      var afterHour = total - day*24*60*60 - hour*60*60;//取得算出小时数后剩余的秒数
      var min = parseInt(afterHour/60);//计算整数分
      let title=1
      if(day!=0){
        title=day+"天前"
      }else if(hour!=0){
        title=hour+"小时前"
      }else if(min!=0){
        title=min+"分钟前"
      }else{
        title="刚刚"
      }
      return title
      
    }
  },
  mounted(){
    this.getData()
    this.getFind(1)
  },
  methods: {
    //去个人首页
    async goRouter(id){
      let data={
        "visitor_user_id":id
      }
      await Post('/user/visitor',this.$store.state.token,data).then(()=>{
        this.$router.push({ path: '/aboutShow',query: { uid: id }})
      }) 
    },
    loadTop() {
      this.$refs.loadmore.onTopLoaded();
    },
    //大图轮播
    showBigImg(item,num){
      let len=item.length
      let data=[]
      for(let i=0;i<len;i++){
        let li={
          image:item[i]
        }
        data.push(li)
      }
      this.imgDataPost={
        data:data,
        static:2,
        num:num
      }
      this.imgDataStatic=true
    },
    //关闭大图轮播
    closeSwiper(){
      this.imgDataStatic=false
    },
    upImg(el){
      if (!el.target.files[0].size) return;
      this.fileList(el.target);
      el.target.value = ''
    },
    fileList(fileList) {
        let files = fileList.files;
        let len = files.length
        if(len<7){
          for (let i = 0; i < len; i++) {
              //判断是否为文件夹
              if (files[i].type != '') {
                  this.fileAdd(files[i]);
              }
          }
        }else{
          alert('最多可传6张照片!')
        }
        
    },
    fileAdd(file) {
        let that=this
        let reader = new FileReader();
        reader.vue = this;
        reader.readAsDataURL(file);
        reader.onload = function () {
            file.src = this.result;
            var cvs = document.getElementById("myCanvas");
            var ctx = cvs.getContext("2d");
            var img = new Image();
            img.src = this.result;
            img.onload = function(){
              var width = img.width,height = img.height;
              var scale = width / height;
              var width1 = 720,height1 = parseInt(width1 / scale);
              ctx.clearRect(0,0,cvs.width,cvs.height);
              cvs.width = width1;
              cvs.height = height1;
              ctx.drawImage(img,0,0,width,height,0,0,width1,height1);
              var base64 = cvs.toDataURL("image/jpeg",0.7)
              ctx.clearRect(0,0,cvs.width,cvs.height)
              that.upImgList.push(base64)
            }
            
        }
    },
    //上传到七牛
    async postQiniu(val){
      let name=(new Date()).valueOf()+''+parseInt(Math.random()*10000);
      let key="user/say/1001/"+name+".jpg"
      let date={
        "key":key,
        "image":val
      }
      await Post('/base/upload/image',this.$store.state.token,date).then((res)=>{
        this.upImgNum++
        this.upImgKey.push(res.data.key)
      }).then(()=>{
        if(this.upImgNum==this.upImgAllNum){
          this.postAll()
        }
      }).catch((err)=>{
        alert(err)
      })
    },
    close(){
      this.postStatic=false
      this.getStatic=false
    },
    //返回上一页
    goBack(){
      this.$router.go(-1)
    },
    //未读信息
    async getData(){
      await Get('/user/say/no/read',this.$store.state.token).then((res)=>{
        this.findNum=res.data
      })
    },
    //未读信息改为已读
    async putData(){
      await Put('/user/say/no/read',this.$store.state.token)
    },
    //个人动态
    async getAllMe(){
      await Get('/user/'+this.$store.state.uid+'/say?_include=user,user_comment',this.$store.state.token).then((res)=>{
        this.dataList=res.data
      }).then(()=>{
        this.putData()
      })
    },
    //发表动态窗
    postNew(){
      this.postStatic=true
    },
    //开始发表
    async postFind(){
      this.$store.dispatch("loading",true)
      let len=this.upImgList.length
      this.upImgAllNum=len
      for(let i=0;i<len;i++){
        this.postQiniu(this.upImgList[i])
      }
      if(len==0){
        let data={
          "say_content":this.find.text
        }
        await Post('/user/say',this.$store.state.token,data).then((reg)=>{
          this.find.text=''
          this.postStatic=false
          this.getFind(1)
        })
        this.$store.dispatch("loading",false)
      }
    },
    async postAll(){
      let upLen=this.upImgKey.length
      let say_image=''
      for(let i=0;i<upLen;i++){
        say_image+=this.upImgKey[i]+','
      }
      say_image = say_image.substr(0,say_image.length-1)
      let dataUp={
        "say_content":this.find.text,
        "say_image":say_image
      }
      await Post('/user/say',this.$store.state.token,dataUp).then((reg)=>{
        this.find.text=''
        this.postStatic=false
        this.upImgList=[]
        this.upImgKey=[]
        this.getFind(1)
      })
      this.$store.dispatch("loading",false)
    },
    //所有动态
    async getFind(val){
      this.$store.dispatch("loading",true)
      
      if(this.$route.query.uid!=undefined){
        //个人动态
        let sql='/user/'+this.$route.query.uid+'/say?_include=user,user_comment,user_like&page='+val
        await Get(sql,this.$store.state.token).then((res)=>{
          this.dataList=res.data
          this.allDataPage=res.meta.pagination.total_pages
        })

      }else{
        //所有动态
        let sql='/user/say?gender='+this.$store.state.gender+'&_include=user,user_comment,user_like&page='+val
        await Get(sql,this.$store.state.token).then((res)=>{
          this.dataList=res.data
          this.allDataPage=res.meta.pagination.total_pages
        }).then(()=>{
          this.getGuanFang()
        })
      }
      
      this.$store.dispatch("loading",false);
    },
    //下一页动态
    async getFindMore(val){
      this.$store.dispatch("loading",true);
      await Get('/user/say?_include=user,user_comment,user_like&page='+val,this.$store.state.token).then((res)=>{
        this.dataList.push(...res.data)
      })
      this.$store.dispatch("loading",false);
    },
    //官方动态
    async getGuanFang(){
      this.$store.dispatch("loading",true);
      await Get('/user/say/system?_include=user,user_comment,user_like',this.$store.state.token).then((res)=>{
        let date=res.data
        this.dataList.splice(2, 0,...res.data);  
      })
      this.$store.dispatch("loading",false);
    },
    //点赞
    async clickZan(item){
      let data={
        "user_say_id":item.id
      }
      await Post('/user/like',this.$store.state.token,data).then((res)=>{
        item.like_count++
        item.me_like_id=res.data.id
      })
    },
    //取消点赞
    async clickCloseZan(item){
      await Delete('/user/like/'+item.me_like_id,this.$store.state.token).then((res)=>{
        item.like_count--
        item.me_like_id=0
      })
    },
    //弹出评论窗
    clickSayBox(val,num){
      this.id=val.id
      this.num=num
      this.getStatic=true
    },
    //发表评论
    async clickSay(){
      let data={
        "user_say_id":this.id,
        "content":this.find.text
      }
      await Post('/user/comment',this.$store.state.token,data).then((res)=>{
        let date={
          user:{
            nickname:this.nickname,
            id:this.uid
          },
          content:this.find.text
        }
        this.dataList[this.num].user_comment.push(date)
        //this.dataList=res.data
      })
      this.find.text=''
      this.getStatic=false
    },
    loadMore () {
      if(this.onPage<this.allDataPage){
        this.onPage++
        this.getFindMore(this.onPage)
      }
      this.$refs.scroller.donePullup()
    },
    refresh () {
      this.loadmoreStatic=true
      this.getFind(1)
      this.$refs.scroller.donePulldown()
    }
  }
  
}
</script>